package com.abel.bigwater.data.jnrq

import com.abel.bigwater.data.BcdString
import io.netty.buffer.ByteBuf
import org.joda.time.DateTime
import kotlin.experimental.and

class TimingData() : JnrqData() {

    val dataHead = byteArrayOf(0)

    var sampleSwitch: Short = 0

    var bakIp2 = ByteArray(8) { 0 }

    var bak3 = ByteArray(4) { 0 }

    var bak4 = ByteArray(2) { 0 }

    var bak5 = ByteArray(2) { 0 }

    /** 服务器时间, 8个长度*/
    var serverTimeStr: BcdString? = null

    var serverTime: DateTime?
        get() = serverTimeStr?.toJnrqDateTime2()
        set(value) {
            serverTimeStr = BcdString.fromJnrqServerTime2(value!!)
        }

    /**
     * 上传周期
     * ssH miH hhH ddH
     */
    var uploadPeriodStr: ByteArray = byteArrayOf(0, 0, 12, 0)

    /** 抄表周期 */
    var readPeriodStr: ByteArray = byteArrayOf(0, 0, 1, 0)

    /** 上传时刻 */
    var uploadClockStr: ByteArray = byteArrayOf(0, 0, 5, 1)

    /** 抄表时刻 */
    var readClockStr: ByteArray = byteArrayOf(0, 0, 6, 1)

    var bak6: Short = 0

    var bak7: Short = 0

    init {
        dataLen = 44
    }

    /**
     * 计算数据长度，针对解析和打包
     */
    override fun computeDataLen(): Int {
        return dataLen!!
    }

    /**
     * 从当前位置写入打包字节流
     */
    override fun fillBuffer(buf: ByteBuf) {
        val tmp = buf.alloc().buffer()

        tmp.writeBytes(dataHead)
        tmp.writeByte(sampleSwitch.toInt())
        tmp.writeBytes(bakIp2)
        tmp.writeBytes(bak3)
        tmp.writeBytes(bak4)
        tmp.writeBytes(bak5)
        tmp.writeBytes(serverTimeStr!!.hexArray)
        tmp.writeBytes(uploadPeriodStr)
        tmp.writeBytes(readPeriodStr)
        tmp.writeBytes(uploadClockStr)
        tmp.writeBytes(readClockStr)
        tmp.writeByte(bak6.toInt())
        tmp.writeByte(bak7.toInt())

        buf.writeBytes(tmp)
    }

    /**
     * 解析字节流，从buf当前位置开始，并且消费其中的字节。
     */
    override fun parseBuffer(buf: ByteBuf) {
        buf.readBytes(dataLen!!).apply {
            fun readByteAsShort() = readByte().toShort() and 0xFF

            skipBytes(1)

            sampleSwitch = readByteAsShort()

            skipBytes(8).skipBytes(4).skipBytes(2).skipBytes(2)

            serverTimeStr = BcdString.create(this, 8)

            skipBytes(4).skipBytes(4).skipBytes(4).skipBytes(4)

            skipBytes(1).skipBytes(1)

        }
    }
}